package com.dhp.security.filter;

import com.dhp.security.entity.MyUserDetails;
import com.dhp.security.utils.TokenUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * @ClassName: TokenLoginFilter
 * @Description: 登录过滤器，继承UsernamePasswordAuthenticationFilter，对用户名密码进行登录校验
 * @Author: dhp
 * @Date: 2020/12/5 21:42
 * @Version: v1.0
 */
public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {
    private RedisTemplate redisTemplate;
    private AuthenticationManager authenticationManager;

    public TokenLoginFilter(AuthenticationManager authenticationManager,RedisTemplate redisTemplate) {
        this.authenticationManager = authenticationManager;
        this.redisTemplate = redisTemplate;
    }

    //通过前端传来的json数据（用户名 密码），解析成我们的java对象，最终得到用户名和密码去进行认证
    @Override
    public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res)
            throws AuthenticationException {
        //只允许post请求
        if(req.getMethod().equals("POST")){
            String username = req.getParameter("username");
            String password = req.getParameter("password");

            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);

            return authenticationManager.authenticate(authRequest);
        }else {
            throw new RuntimeException("only post requests are allowed to login");
        }

    }

    //若认证成功，根据用户名生成token返回给前端。并以用户名为key，权限列表为value的形式存入redis缓存中
    @Override
    protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain,
                                            Authentication auth) throws IOException, ServletException {

        MyUserDetails myUserDetails = (MyUserDetails)auth.getPrincipal();

        String token = TokenUtils.createToken(myUserDetails.getUsername());

        redisTemplate.opsForValue().set(myUserDetails.getUsername(),myUserDetails.getPermissionValueList());

        res.getWriter().println(token);
    }

    /**
     * 登录失败
     * @param request
     * @param response
     * @param e
     * @throws IOException
     * @throws ServletException
     */
    //若认证失败，则返回错误信息给前端
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
                                              AuthenticationException e) throws IOException, ServletException {
        response.getWriter().print("login error");
    }
}
